package com.example.shop_2208.comment

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.shop_2208.R
import com.example.shop_2208.adapter.CommentAdapter
import com.example.shop_2208.databinding.ActivityCommentBinding
import com.example.shop_2208.entity.CommentEnity
import com.example.shop_2208.mvvm.BaseActivity

@Route(path = "/app/CommentActivity")
class CommentActivity : BaseActivity<ActivityCommentBinding,CommentViewModel>() {
    lateinit var commentAdapter: CommentAdapter
    var index = 0
    override fun initData() {
       viewModel.getSuccess.observe(this){
           if(it.code==200){
               commentAdapter.data.clear()
               commentAdapter.data.addAll(it.data)
               commentAdapter.notifyDataSetChanged()
           }
       }
        viewModel.getChildSuccess.observe(this){
            if(it.code==200){
                commentAdapter.data.addAll(index,it.data)
                commentAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun initView() {
        commentAdapter = CommentAdapter()
        binding.rvComment.adapter = commentAdapter
        binding.rvComment.layoutManager = LinearLayoutManager(this)

        viewModel.getComment()
        //点击加载更多实现加载二级评论
        commentAdapter.addChildClickViewIds(R.id.comment_more)
        commentAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id){
                R.id.comment_more->{
                    viewModel.getChildComment(commentAdapter.data[position].rootid)
                    index = position //记录当前点击的下标
                }
            }
        }

        //点击发送按钮，实现发送评论
        binding.btnComment.setOnClickListener {
            val msg = binding.etComment.text.toString()
            viewModel.comment(msg)

           viewModel.commentSuccess.observe(this){
               if(it.code==200){
                   commentAdapter.data.add(0,it.data[0])
                   commentAdapter.notifyDataSetChanged()
               }
           }
            binding.etComment.setText("")
        }
    }

    override fun getViewModel(): Class<CommentViewModel>  = CommentViewModel::class.java

    override fun getLayout(): Int  = R.layout.activity_comment

}